package cn.zoujiedev.netty.core.handler;

import cn.zoujiedev.netty.core.bean.Header;
import cn.zoujiedev.netty.core.bean.MessageType;
import cn.zoujiedev.netty.core.bean.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @Classname LoginAuthReqHandler
 * @Description
 * @Date 2022-11-3 15:59
 * @Created by zoujie
 */
@Slf4j
public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.writeAndFlush(buildLoginReq());
    log.info("send auth req to server");
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    if(message.getHeader() != null && message.getHeader().getType() == MessageType.HAND_SHAKE_RESPONSE){
      byte res = (byte)message.getBody();
      if(res != 0){
        //握手失败,关闭连接
        ctx.close();
      }else {
        log.info("Login is ok : {}", message);
        ctx.fireChannelRead(msg);
      }
    }else {
      ctx.fireChannelRead(msg);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.fireExceptionCaught(cause);
  }

  private NettyMessage buildLoginReq(){
    NettyMessage nettyMessage = new NettyMessage();

    Header h = new Header();
    h.setType(MessageType.HAND_SHAKE_REQUEST);
    nettyMessage.setHeader(h);
    return nettyMessage;
  }
}
